package com.ttxz.sample.vm

import androidx.lifecycle.viewModelScope
import com.ttxz.common.base.viewmodel.BaseViewModel
import com.ttxz.common.http.HttpResponse
import com.ttxz.common.utils.log.LogUtil
import com.ttxz.sample.HttpResponseLiveData
import com.ttxz.sample.IHttpResponseObserver
import com.ttxz.sample.bean.ArticleListBean
import com.ttxz.sample.bean.ArticleListItemBean
import com.ttxz.sample.bean.BannerBean
import com.ttxz.sample.db.dao.BannerDao
import com.ttxz.sample.model.MainModel
import kotlinx.coroutines.delay
import kotlinx.coroutines.launch
import kotlinx.coroutines.runBlocking

class MainVM : BaseViewModel<MainModel>() {

    fun getBannerData(): HttpResponseLiveData<List<BannerBean>> {
        val responseLiveData = HttpResponseLiveData<List<BannerBean>>()
        //方式一：
//        viewModelScope.launch {
//            responseLiveData.value = model?.getBannerData()
//        }
        //方式二：自带loading弹框（建议使用）
        launchWithLoading(requestBlock = {
            //TODO:测试，接口太快
            delay(2000)
            val resultData = model?.getBannerData()
            //存储数据到数据库
            resultData?.data?.let {
                model?.insertBannerDataForDb(it)
            }
            resultData
        }, resultCallback = {
            responseLiveData.value = it
        })

        return responseLiveData
    }

    fun getBannerDataForDB():List<BannerBean>{
        return runBlocking {
            model?.getBannerDataFoDB()?: mutableListOf()
        }
    }

    fun getArticleListData(): HttpResponseLiveData<ArticleListBean> {
        val responseLiveData = HttpResponseLiveData<ArticleListBean>()
        launchWithLoading(requestBlock = {
            //TODO:测试，接口太快
            delay(2000)
            val resultData = model?.getArticleListData()
            //存储数据到数据库
            resultData?.data?.datas?.let {
                model?.insertArticleListDataForDb(it)
            }
            resultData
        }, resultCallback = {
            responseLiveData.value = it
        })
        return responseLiveData
    }

    fun getArticleListDataForDB():List<ArticleListItemBean>{
        return runBlocking {
            model?.getArticleListDataForDB()?: mutableListOf()
        }
    }

}